using AutoMapper;
using MediatR;
using ThreeTeams.API.Application.Command.BoxTypeManageMentCommand;
using ThreeTeams.Domain;
using ThreeTeams.ErrorCode;
using ThreeTeams.Infrastructure;

namespace ThreeTeams.API.Application.CommandHandler.BoxTypeManageMentCommandHandler
{
    public class UpdateBoxTypeCommandHandler : IRequestHandler<UpdateBoxTypeCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<BoxType> baseRepository;
        private readonly IMapper mapper;

        public UpdateBoxTypeCommandHandler(IBaseRepository<BoxType> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateBoxTypeCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            var existingBoxType = baseRepository.GetAll().FirstOrDefault(p => p.Id == request.Id);

            if (existingBoxType == null)
            {
                result.Code = ApiEnum.Fail;
                result.Message = "没有找到箱子型号.";
                return result;
            }

            var updatedBoxType = mapper.Map(request, existingBoxType);

            var updateResult = await baseRepository.Update(updatedBoxType);

            result.Code = updateResult > 0 ? ApiEnum.Ok : ApiEnum.Fail;
            result.Data = updateResult;
            result.Message = updateResult > 0 ? "修改成功" : "修改失败";

            return result;
        }
    }
} 